<?php
	//this program will run every hour
	ini_set('display_errors', 1);
	error_reporting(E_ALL | E_STRICT);
	set_time_limit(60*60);
	ini_set('memory_limit', '128M');
	date_default_timezone_set('America/New_York');
	
	require_once "config.php";
	require_once dirname(__FILE__)."/util/connection.class.php";
	$dbconn = Connection::getInstance();
	
	$campaigns = getAllCampaignStatus($dbconn);
	$pixels = getAllPixelStatus($dbconn);
	
	foreach ($pixels as $pixel) {
		$position = getPosition($pixel['position']);
		$cam = $pixel['campaign'];
		$pub = $pixel['pub'];
		$pla = $pixel['pla'];
		foreach ($campaigns as $campaign) {
			if ($campaign['cam'] == $cam && $campaign['pub'] == $pub && $campaign['pla'] == $pla) {
				$currentFired = $campaign[$position];
				$totalLandings = $campaign['landing'];
				$firedPeak = $pixel['peak'] * $totalLandings / 100; 
				$suppress = $currentFired - $firedPeak;
				$suppress = ($suppress > 0) ? ceil($suppress) : 0;
				$sql = 'UPDATE `pixel_managment` SET `current_fired` = ?, `total_landings` = ?, `suppress` = ? WHERE `campaign` =  ? and `pub` = ? and `pla` = ?';
				try{
					$result =  $dbconn->execute($sql, array($currentFired, $totalLandings, $suppress, $cam, $pub, $pla));
				} catch (Exception $e) {
					QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
					throw new Model_Exception($e->getMessage(), $e->getCode());
				}
				break;
			}
		}
	}
	
	function getAllCampaignStatus(Connection $db) {
		$sql = 'SELECT SUM( basic_reg ) AS basic_reg, SUM( full_reg ) AS full_reg, SUM( landing ) AS landing, cam, pub, pla FROM `site_data` WHERE `time` > ' . strtotime(date('Y-m-d')) .  ' GROUP BY cam, pub, pla';
		try{
			$result =  $db->query($sql);
		} catch (Exception $e) {
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
		if (count($result) > 0) {
			
			return $result;
		}
		return NULl;
	}
	
	function getAllPixelStatus(Connection $db) {
		$sql = 'SELECT * FROM `pixel_managment`';
		try{
			return $db->query($sql);
		} catch (Exception $e) {
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	function getPosition($pos) {
		$position = '';
		switch ($pos) {
			case 0:
				$position = 'basic_reg';
				break;
			case 1:
				$position = 'full_reg';
				break;
		}
		return $position;
	}
	